package com.wyp.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wyp.pojo.Apartments;
import com.wyp.pojo.Testpapers;
import com.wyp.service.impl.ApartmentsServiceImpl;
import com.wyp.service.impl.QuestionsServiceImpl;
import com.wyp.service.impl.ScoresServiceImpl;
import com.wyp.service.impl.TestpapersServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.*;

@Controller
@RequestMapping("/admin")
public class TestpaperManController {

    //随机数种子
    private long randomnessSeed = System.currentTimeMillis() ^ (long) this.hashCode();
    private Random sourceOfRandomness = new Random(randomnessSeed);

    @Autowired
    private TestpapersServiceImpl testpapersService;

    @Autowired
    private QuestionsServiceImpl questionsService;

    @Autowired
    private ScoresServiceImpl scoresService;

    @Autowired
    private ApartmentsServiceImpl apartmentsService;

    @RequestMapping("/testpaper_manage.html")
    public String tologin(Model model,
                          @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "4") int pageSize) {
        if (pageNum <= 0) {
            pageNum = 1;
        }
        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        PageHelper.startPage(pageNum, pageSize);
        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页，除非再次调用PageHelper.startPage
        try {
            List<Map<String, Object>> testpapersList = testpapersService.qureyAllTestpapers();
            //3.使用PageInfo包装查询后的结果,5是连续显示的条数,结果list类型是Page<E>
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(testpapersList, pageSize);
            //4.使用model/map/modelandview等带回前端
            model.addAttribute("pageInfo", pageInfo);
        } finally {
            PageHelper.clearPage(); //清理 ThreadLocal 存储的分页参数,保证线程安全
        }
        return "admin/testpaper/testpaper_manage";
    }

    @GetMapping("/testpaper_add.html")
    public String totestpadd(Model model) {
        List<Apartments> apartments = apartmentsService.qureyAllApartment();
        model.addAttribute("apartments", apartments);
        return "admin/testpaper/testpaper_add";
    }

    @PostMapping("/testpaper_add.html")
    public String testpadd(
            Testpapers testpapers
    ) {
        if (testpapers.isType()) {
            String testpapercontent = "";
            int point = 0;
            List<Map<String, Object>> Fquestions = new ArrayList<Map<String, Object>>();
            Fquestions.addAll(getquestionsbytype(testpapers.getSinglenum(), 1, testpapers.getApartmentid()));
            Fquestions.addAll(getquestionsbytype(testpapers.getMultiplenum(), 2, testpapers.getApartmentid()));
            Fquestions.addAll(getquestionsbytype(testpapers.getJudgenum(), 3, testpapers.getApartmentid()));
            for (Map<String, Object> question : Fquestions) {
                if (testpapercontent.equals("")) {
                    testpapercontent = "" + (int)question.get("questionid");
                } else {
                    testpapercontent = testpapercontent + "," + (int)question.get("questionid");
                }
                point = point + (int)question.get("point");
            }
            testpapers.setTestpapercontent(testpapercontent);
            testpapers.setTotalpoint(point);
            testpapers.setStatus(1);
            testpapersService.addTestpapers(testpapers);
        } else {
            testpapers.setTotalpoint(0);
            testpapers.setStatus(1);
            testpapers.setTestpapercontent("");
            testpapersService.addTestpapers(testpapers);
        }
        return "redirect:/admin/testpaper_manage.html";
    }

    private List<Map<String, Object>> getquestionsbytype(int questionnum, int type, int apartmentid) {
        List<Map<String, Object>> Aquestions = questionsService.qureyQuestionsByType(type, apartmentid);
        Collections.shuffle(Aquestions, this.sourceOfRandomness);
        return Aquestions.subList(0, questionnum);
    }

    @RequestMapping("/testpaper_information.html/{id}")
    public String totpinfo(
            @PathVariable("id") int id,
            Model model
    ) {
        Map<String, Object> testpaper = testpapersService.qureyTestpapersByid(id);
        String content = (String) testpaper.get("testpapercontent");
        String[] questionsid = content.split(",");
        List<Map<String, Object>> Squestions = new ArrayList<>();
        List<Map<String, Object>> Mquestions = new ArrayList<>();
        List<Map<String, Object>> Jquestions = new ArrayList<>();
        for (String questionid : questionsid) {
            if (!questionid.equals("")) {
                Map<String, Object> question = questionsService.qureyQuestionsByid(Integer.parseInt(questionid));
                if ((int)question.get("type") == 1) {
                    Squestions.add(question);
                }
                if ((int)question.get("type") == 2) {
                    Mquestions.add(question);
                }
                if ((int)question.get("type") == 3) {
                    Jquestions.add(question);
                }
            }
        }
        model.addAttribute("testpaper", testpaper);
        model.addAttribute("Squestions", Squestions);
        model.addAttribute("Mquestions", Mquestions);
        model.addAttribute("Jquestions", Jquestions);
        return "admin/testpaper/testpaper_information";
    }

    @GetMapping("/testpaper_delete.html/{id}")
    public String todeletepaper(
            Model model,
            @PathVariable("id") int id
    ) {
        List<Map<String, Object>> scores = scoresService.qureyAllScores();
        for (Map<String, Object> score : scores) {
            if ((int)score.get("testpaperid")==id) {
                scoresService.deleteScores((int) score.get("scoresid"));
            }
        }
        testpapersService.deleteTestpapers(id);
        return "redirect:/admin/testpaper_manage.html";
    }

    @RequestMapping("/testpaper_qurey.html")
    public String toqureytestlibinfo(
            @Nullable @RequestParam("qureymessage") String qureymessage
    ) throws UnsupportedEncodingException {
        if (qureymessage != null && !(qureymessage.equals(""))) {
            qureymessage = new String(qureymessage.getBytes("utf-8"), "iso-8859-1");
            return "redirect:/admin/testpaper_qurey.html/" + qureymessage;
        } else {
            return "redirect:/admin/testpaper_manage.html";
        }
    }

    @RequestMapping("/testpaper_qurey.html/{qureymessage}")
    public String qureytestlibinfo(
            Model model,
            @Nullable @PathVariable("qureymessage") String qureymessage,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "4") int pageSize
    ) {
        if (pageNum <= 0) {
            pageNum = 1;
        }
        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        PageHelper.startPage(pageNum, pageSize);
        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页，除非再次调用PageHelper.startPage
        try {
            if (qureymessage == null || qureymessage.equals("")) {
                List<Map<String, Object>> testpapers = testpapersService.qureyAllTestpapers();
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(testpapers, pageSize);
                model.addAttribute("pageInfo", pageInfo);
            } else {
                List<Map<String, Object>> testpapers = testpapersService.qureyTestpapersByTestpapername(qureymessage);
                //3.使用PageInfo包装查询后的结果,5是连续显示的条数,结果list类型是Page<E>
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(testpapers, pageSize);
                //4.使用model/map/modelandview等带回前端
                model.addAttribute("pageInfo", pageInfo);
            }
        } finally {
            PageHelper.clearPage(); //清理 ThreadLocal 存储的分页参数,保证线程安全
        }
        return "admin/testpaper/testpaper_manage";
    }
}
